package cn.xing.modules.app.service.impl;


import cn.xing.common.utils.PageUtils;
import cn.xing.common.utils.Query;
import cn.xing.modules.app.dao.UserDao;
import cn.xing.modules.app.entity.UserEntity;
import cn.xing.modules.app.form.LoginForm;
import cn.xing.modules.app.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.UUID;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public UserEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
    }

    @Override
    public long loginOrRegister(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());

        // 不存在该用户,则注册一个
        if (user == null) {
            user = new UserEntity();
            user.setMobile(form.getMobile());
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            user.setUsername("user_"+ UUID.randomUUID().toString().substring(0,10));

            this.baseMapper.insert(user);
        }

        //密码错误
        // if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
        //     throw new RRException("手机号或密码错误");
        // }

        return user.getUserId();
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }
}
